package com.yunxiao.cloud.mail.service.impl;

import com.yunxiao.cloud.mail.constant.MailConstant;
import com.yunxiao.cloud.mail.entity.Mail;
import com.yunxiao.cloud.mail.factory.MailSendFactory;
import com.yunxiao.cloud.mail.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Objects;

/**
 * <p>
 * 邮件表 服务实现类
 * </p>
 *
 * @author yunxiao
 * @since 2020-01-16
 */
@Service
public class MailServiceImpl implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);


    static {
        System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
    }

    @Autowired
    public Configuration freemarkerConfiguration;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Override
    public int sendEmail(Mail mail) {
        try {
            logger.info("发送邮件：{}", mail.getContent());
            MimeMessage message = MailSendFactory.getMailSender(mail.getFromEmail(), mail.getPassword()).createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
            //这里可以自定义发信名称比如：
            helper.setFrom(mail.getFromEmail());
            String[] toMailArr = mail.getToEmail().split(",");
            if (toMailArr.length > 1) {
                helper.setTo(toMailArr);
            } else {
                helper.setTo(mail.getToEmail());
            }
            if (mail.getCopyTo() != null) {
                String[] copyArr = mail.getCopyTo().split(",");
                if (copyArr.length > 1) {
                    helper.setCc(copyArr);
                } else {
                    helper.setCc(mail.getCopyTo());
                }
            }

            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), mail.isHtml());

            // 发送附件
            sendAttachment(mail, helper);
            MailSendFactory.getMailSender(mail.getFromEmail(), mail.getPassword()).send(message);
            return 0;
        } catch (Exception e) {
            logger.error("sendEmail error: ", e);
            return -1;
        }
    }

    @Override
    public int sendFreemarker(Mail mail) {
        try {
            logger.info("发送模板邮件：{}", mail.getContent());
            MimeMessage message = MailSendFactory.getMailSender(mail.getFromEmail(), mail.getPassword()).createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            //这里可以自定义发信名称比如：爪哇笔记
            helper.setFrom(mail.getFromEmail());
            String[] toMailArr = mail.getToEmail().split(",");
            if (toMailArr.length > 1) {
                helper.setTo(toMailArr);
            } else {
                helper.setTo(mail.getToEmail());
            }
            if (mail.getCopyTo() != null) {
                String[] copyArr = mail.getCopyTo().split(",");
                if (copyArr.length > 1) {
                    helper.setCc(copyArr);
                } else {
                    helper.setCc(mail.getCopyTo());
                }
            }
            helper.setSubject(mail.getSubject());

            Template template = freemarkerConfiguration.getTemplate(mail.getTemplate());
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(
                    template, mail.getTemplateMap());
            helper.setText(text, true);

            // 发送附件
            sendAttachment(mail, helper);

            MailSendFactory.getMailSender(mail.getFromEmail(), mail.getPassword()).send(message);

            return 0;
        } catch (Exception e) {
            logger.error("sendFreemarker error: ", e);
            return -1;
        }
    }

    @Override
    public int sendThymeleaf(Mail mail) {
        try {
            logger.info("发送Thymeleaf模板邮件：{}", mail.getContent());
            MimeMessage message = MailSendFactory.getMailSender(mail.getFromEmail(), mail.getPassword()).createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
            //这里可以自定义发信名称比如：爪哇笔记
            helper.setFrom(mail.getFromEmail());

            String[] toMailArr = mail.getToEmail().split(",");
            if (toMailArr.length > 1) {
                helper.setTo(toMailArr);
            } else {
                helper.setTo(mail.getToEmail());
            }
            if (mail.getCopyTo() != null) {
                String[] copyArr = mail.getCopyTo().split(",");
                if (copyArr.length > 1) {
                    helper.setCc(copyArr);
                } else {
                    helper.setCc(mail.getCopyTo());
                }
            }
            helper.setSubject(mail.getSubject());

            String text = templateEngine.process(mail.getTemplate(), mail.getContext());
            helper.setText(text, true);

            sendAttachment(mail, helper);

            MailSendFactory.getMailSender(mail.getFromEmail(), mail.getPassword()).send(message);
            return 0;
        } catch (Exception e) {
            logger.error("sendThymeleaf error: ", e);
            return -1;
        }
    }

    private void sendAttachment(Mail mail, MimeMessageHelper helper) throws MessagingException {
        // 发送附件
        if (!CollectionUtils.isEmpty(mail.getEmailAttachment())) {
            mail.getEmailAttachment().stream().filter(Objects::nonNull).forEach(bean -> {
                FileSystemResource file = new FileSystemResource(new File(bean.getFilePath()));
                try {
                    if (MailConstant.FILE_NAME.equals(bean.getFileName())){
                        helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);
                    } else {
                        helper.addAttachment(bean.getFileName(), file);
                    }
                } catch (MessagingException e) {
                    logger.error("==添加附件失败, filename:{}, filePath:{}", bean.getFileName(), bean.getFilePath());
                }
            });
        }
    }

}
